const websocket = require("ws")

const ws = new websocket.Server({
    port:8000 
})

let clinets ={}//28
let clinetNum = 0

ws.on("connection",(client)=>{
    client.name = ++clinetNum
    clinets[client.name] = client 
    client.on("message",(msg)=>{
        console.log("用户"+client.name+"说："+msg);
        broadcast(client,msg)
    })

    client.on("error",(err)=>{
        if(err){
            console.log(err);  
        }
    })

    client.on("close",()=>{
        broadcastQuite(client)
        console.log("用户"+client.name+"下线了！");
        delete clinets[client.name] 
    })
})

function broadcast(client,msg){
    for(let key in clinets){
        clinets[key].send("用户"+client.name+"说："+msg)
    }
}
function broadcastQuite(client){
    for(let key in clinets){
        clinets[key].send("系统提示：用户"+client.name+"下线了！")
    }
}